import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:projectfluttershengyihuatong/category/category.dart';
import 'package:projectfluttershengyihuatong/route.dart';
import 'package:projectfluttershengyihuatong/tool/extension_int.dart';
import '../tool/tool.dart';
import '../service/loginService/logginservice.dart';
import '../tool/public_color.dart';
import 'package:projectfluttershengyihuatong/category/catetory_controller.dart';
import '../tool/Toast.dart';
class Login extends StatefulWidget {
  const Login({super.key, this.loginFinished,required this.type});

  final VoidCallback? loginFinished;
  ///type = 2 开机启动第一次登录。

  final int type;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return LoginState();
  }
}

class LoginState extends State<Login> {
  // 如何同时获取用户名和密码的表单信息？
  // 如果我们调用Form的State对象的save方法，就会调用Form中放入的TextFormField的onSave回调：
  // 在Flutter可以获取一个通过一个引用获取一个StatefulWidget的State对象
  final _fromKey = GlobalKey<FormState>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(seconds: 1)).then((value){
      Get.find<LoginService>().getPhone();
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      //设置导航栏高度
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(44),
        child: AppBar(
          title: const Text(
            "登录",
            style: TextStyle(
              color: Colors.black87,
            ),
          ),
          //导航栏背景颜色
          backgroundColor: Colors.white,
          //隐藏掉阴影
          elevation: 0,
          leading: widget.type == 1 ? CloseButton(
            onPressed: () {
              //返回上一个页面
              Get.back();
            },
            color: Colors.black54,
          ) : Container(),
          //设置返回按钮
        ),
      ),
      body: Container(
        color: Colors.white,
        child: ListView(
          padding: const EdgeInsets.fromLTRB(30, 60, 30, 30),
          children: [
            Image.asset(
              assetImage("ico_logo"),
              width: 113.adapt(),
              height: 80.adapt(),
            ),
            const SizedBox(
              height: 40,
            ),
            _buildUserName(),
            const SizedBox(
              height: 10,
            ),
            buildPasswordTextField(),
            _buildForgetPasswordAndRegister(),
            const SizedBox(
              height: 10,
            ),
            _buildLoginBtn(context),
            _buildPrivateAndUser(context)
          ],
        ),
      ),
    );
  }

  //登录按钮
  Widget _buildLoginBtn(BuildContext context) {
    return OutlinedButton(

        onPressed: () async {
          //  执行登录方法
          if (_userName.isEmpty) {
            ToastManager.show(context, "请输入用户名");
            return;
          }
          if (_password.isEmpty) {
            ToastManager.show(context, "请输入密码");

            return;
          }
          // final password = EncryptTool.encryptAES_(_password);
          // final params = {
          //   "grant_type":"password",
          //   "password": _password,
          //   "scope":"server",
          //   "username": _userName
          // };
          LoginService.login(_userName, _password).then((value) async {
            if (value.ret == 1) {
              if(widget.type == 2){
                // LoginService.getInstance().update([LoginService.LOGIN]);
                LoginService.getInstance().isShowLoginPage = false;
                if(CatetoryController.getInstance().leiModel == null){
                   final result = await Get.offAllNamed(RouteNames.CATEGORYPAGE, arguments: 1);


                }else {
                  LoginService.getInstance().update([LoginService.LOGIN]);
                }
              }else {
                Get.back();
                LoginService.getInstance().update([LoginService.LOGIN2]);

                LoginService.getInstance().isShowLoginPage = false;
              }
            } else {
              //   登录视频，重复登录
            }
          }).onError((error, stackTrace) {
            if (kDebugMode) {
              print(error.toString());
            }
          });
        },
        style: ButtonStyle(
          backgroundColor: MaterialStatePropertyAll<Color>(primaryColor),
          side: const MaterialStatePropertyAll<BorderSide>(BorderSide.none),
        ),
        child: Text(
          "登录",
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
          ),
        ));

    return ElevatedButton(
      style: ButtonStyle(
          // 50DB8E
          backgroundColor: MaterialStateProperty.all(color01CAA8),
          //StadiumBorder 圆角
          shape: MaterialStateProperty.all(
              const StadiumBorder(side: BorderSide(style: BorderStyle.none)))),
      child: const Text(
        "登录",
        style: TextStyle(color: Colors.white, fontSize: 14),
      ),
      onPressed: () {
        //  执行登录方法
        if (_userName.isEmpty) {
          showAlert(context);
          return;
        }
        if (_password.isEmpty) {
          showAlert(context);
          return;
        }
        // final password = EncryptTool.encryptAES_(_password);
        // final params = {
        //   "grant_type":"password",
        //   "password": _password,
        //   "scope":"server",
        //   "username": _userName
        // };
        LoginService.login(_userName, _password).then((value) {
          if (value.ret == 1) {
            //   登录成功。判断有没有选择门类
            if (Get.find<CatetoryController>().leiModel == null) {
              Get.toNamed(RouteNames.CATEGORYPAGE);
            } else {
              Get.back();
            }
          } else {
            //   登录视频，重复登录
          }
        }).onError((error, stackTrace) {
          if (kDebugMode) {
            print(error.toString());
          }
        });
      },
    );
  }

  void showAlert(BuildContext context, {String? title, String? detail}) async {
    var result = await showDialog(
        context: context,
        barrierDismissible: true,
        builder: (context) {
          return AlertDialog(
            elevation: 10,
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20),
            ),
            title:  Text(title??""),
            content:  Padding(
              padding: const EdgeInsets.all(8),
              child: Text(detail??""),
            ),
            contentTextStyle: const TextStyle(color: Colors.black),
            actions: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text("确定"),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: ElevatedButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text("取消"),
                ),
              ),
            ],
            actionsOverflowButtonSpacing: 60,
            actionsAlignment: MainAxisAlignment.spaceBetween,
          );
        },
        barrierLabel: "给屏障定义一个name",
        anchorPoint: const Offset(1, 2));
  }

  var _isAgree = false;

  //用户协议和隐私政策
  Widget _buildPrivateAndUser(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        IconButton(
            onPressed: () {
              _isAgree = !_isAgree;
              setState(() {});
            },
            color: Colors.teal,
            iconSize: 30,
            icon: Image.asset(
              assetImage(_isAgree ? "ico_select_s" : "ico_select_n"),
              width: 15,
              height: 15,
            )),
        Expanded(
            child: Text.rich(
          TextSpan(
              text: '阅读并同意',
              style: TextStyle(fontSize: 14, color: colorB5),
              children: [
                TextSpan(
                  text: '《用户协议》',
                  style: TextStyle(color: color01CAA8),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      Get.toNamed(RouteNames.WEBPAGE, arguments: {"url": "", "title":"用户协议"});
                    },
                ),
                const TextSpan(text: '和'),
                TextSpan(
                  text: '《隐私政策》',
                  style: TextStyle(color: color01CAA8),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      // Navigator.of(context)
                      //     .push(MaterialPageRoute(builder: (context) {
                      //   return WebViewPage(
                      //       title: '《隐私政策》', url: 'https://flutter.dev');
                      // }));
                      Get.toNamed(RouteNames.WEBPAGE, arguments: {"url": "", "title":"用户协议"});

                    },
                ),
              ]),
        ))
      ],
    );
  }

  //创建忘记密码和注册按钮
  Widget _buildForgetPasswordAndRegister() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        TextButton(
            onPressed: () {
              _forgetPassword();
            },
            child: const Text(
              "忘记密码?",
              style: TextStyle(color: Colors.lightBlue, fontSize: 14),
            )),
        TextButton(
            onPressed: () {
              _registerAction();
            },
            child: const Text(
              "注册",
              style: TextStyle(color: Colors.lightBlue, fontSize: 14),
            ))
      ],
    );
  }

  //MARK:  忘记密码
  _forgetPassword() {}

  _registerAction() {}

  String _userName = "";
  late TextEditingController userNameContainer = TextEditingController();

//  用户名
  Widget _buildUserName() {
    final lineBorder = UnderlineInputBorder(
      borderSide: BorderSide(
        color: colorf1,
        width: 1
      )
    );
    return GetBuilder<LoginService>(
        id: LoginService.savePhone,
        builder: (controller) {
          userNameContainer.text = controller.phone;
          _userName = controller.phone;
          return TextFormField(
            controller: userNameContainer,
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.fromLTRB(5, 10, 10, 10),
              hintText: "请输入账号",
              hintStyle: const TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
              focusedBorder: lineBorder,
              border: lineBorder,
              enabledBorder: lineBorder,
              errorBorder: const UnderlineInputBorder(
                  borderSide: BorderSide(color: Color(0xff999999))),
              disabledBorder: lineBorder,

              prefixIcon: IconButton(
                onPressed: () {},
                color: Colors.teal,
                iconSize: 40.adapt(),
                icon: Image.asset(
                  assetImage("ico_phone"),
                  width: 16.adapt(),
                  height: 20.adapt(),
                ),
              ),
            ),
            onChanged: (text){
              _userName = text;
            },
            //  用于对输入框中的表单内容进行校验
          );
        });
  }

  Widget buildUserNameTextField() {
    final lineBorder = UnderlineInputBorder(
        borderSide: BorderSide(
            color: colorf1,
            width: 1
        )
    );
    return TextFormField(
      maxLength: 10,
      //输入最大的字符数量
      maxLines: 1,
      //行数
      // maxLengthEnforcement: MaxLengthEnforcement.truncateAfterCompositionEnds,
      autofocus: false,
      //是否自动对焦
      keyboardType: TextInputType.text,
      //设置输入模式，手机号，邮箱，数字
      decoration: InputDecoration(
        hintText: "请输入用户名",
        //输入框提示语内容
        //输入框的提示语样式
        hintStyle:
            const TextStyle(color: Color.fromARGB(255, 189, 189, 189), fontSize: 14),
        //提示框里面的内容距离边框的距离
        contentPadding: const EdgeInsets.fromLTRB(0, 10, 10, 10),
        //左侧手机icon
        icon: const Icon(
          Icons.ad_units_rounded,
          color: Colors.grey,
        ),
        labelText: "设置输入框的描述信息，会遮盖hinttext",
        labelStyle: const TextStyle(color: Colors.green, fontSize: 12),
        errorText: "输入内容错误的时候，错误提示信息",
        errorStyle: const TextStyle(color: Colors.red, fontSize: 14),
        //设置输入框的前置图标，使用方法与icon属性一样，但是图标位于icon属性图标的右侧
        prefixIcon: const Icon(
          Icons.phone,
          color: Colors.blue,
        ),
        //设置输入框内的前置文本，该属性可以与prefixStyle属性配合使用，prefixStyle属性用于
        // 设置输人框内前置的文本样式，它的属性值为TextStyle类型。
        prefixText: "手机号",
        prefixStyle: const TextStyle(color: Colors.black87),
        suffixText: "中国",
        suffixStyle: const TextStyle(color: Colors.red),
        suffixIcon: const Icon(
          Icons.flag,
          color: Colors.green,
        ),
        counterText: "请输入13位手机号码",
        counterStyle: const TextStyle(color: Colors.grey),
        //  输入框的左侧内容
        // prefix: Container(
        //   child: const Icon(Icons.password_outlined),
        // ),
        //输入框右侧的内容
        // suffix:
        //  输入框未选中的时候，输入框的样式,底部边框的样式
        enabledBorder: lineBorder,
        border: lineBorder,
        focusedBorder: lineBorder,
        focusedErrorBorder: lineBorder,
        disabledBorder: lineBorder,

        errorBorder:
            const UnderlineInputBorder(borderSide: BorderSide(color: Colors.black12)),
      ),
      //  输入框内的提示语内容
    );
  }

  bool _isShowPassword = false;
  String _password = "";

  Widget buildPasswordTextField() {
    final lineborder =  UnderlineInputBorder(
      borderSide: BorderSide(
        color: colorf1,
        width: 1,
      ),
    );
    return TextFormField(
      obscureText: _isShowPassword,
      decoration: InputDecoration(
        contentPadding: const EdgeInsets.fromLTRB(5, 10, 10, 10),
        hintText: "请输入密码",
        hintStyle: const TextStyle(color: Colors.grey),
        enabledBorder:lineborder,
        disabledBorder: lineborder,
        errorBorder: lineborder,
        focusedBorder: lineborder,
        focusedErrorBorder: lineborder,
        suffixIcon: buildPasswordSuffixIcon(),
        prefixIcon: buildpasswordPrefixIcon(),
      ),
      onChanged: (text){
        _password = text;
      },
    );
  }

  IconButton buildPasswordSuffixIcon() {
    return IconButton(
        color: Colors.teal,
        icon: ImageIcon(
          _isShowPassword
              ? AssetImage(assetImage("ico_show_password"))
              : AssetImage(assetImage("ico_hide_password")),
          size: 21,
        ),
        iconSize: 30,
        onPressed: () {
          _isShowPassword = !_isShowPassword;
          setState(() {});
        });
  }

  IconButton buildpasswordPrefixIcon() {
    return IconButton(
      onPressed: () {},
      color: Colors.teal,
      iconSize: 40.adapt(),
      icon: Image.asset(
        assetImage("ico_password"),
        width: 16.adapt(),
        height: 20.adapt(),
      ),
    );
  }
}

/**
 *InputDecoration控制输人框提示信息样式的常用属性
    如下:
    (1)icon:设置输人框左侧显示图标。
    (2) labelText:设置输入框描述信息，当输入框获取焦点时默认会浮动到上方。
    (3) helperText: 设置输人框辅助信息，位于输人框下方。
    (4)errorText:设置输人框中内容输人错误时的错误提示信息。
    (5) hintText: 设置输人框内的提示信息。该属性可以与hintStyle属性配合使用，intStyle属性用于设置输人框内提示信息的文本样式，它的属性值为TextStyle类型。
    (6)prefixlcon:设置输人框内的前置图标，使用方法与icon属性一样，但图标位于icon属性所设置图标的右侧。
    (7) prefixText: 设置输入框内的前置文本，该属性可以与prefixStyle属性配合使用，prefixStyle属性用于 设置输人框内前置的文本样式，它的属性值为TextStyle类型。
    (8)suffixlcon:设置输人框内的后置图标，使用方法与icon属性一样，但图标位于输入框的右侧。
    (9) suffixText: 设置输 人框内的后置文本，该属性可以与suffixStyle属性配合使用，prefixStyle属性 用于设置输入框内后置的文本样式，它的属性值为TextStyle类型。
    (10) counterText: 设置输人框右下方显示的文本，常用于显示输入的字符数量，该属性可以与counterStyle属性配合使用，counterStyle属性用于设置输人框右下方的文本样式，它的属性值为TextStyle类型。
    (11) counter: 设置输人框右下方的Widget小组件， 但不能与counterText同时使用.
    (12) filled: 设置填充输人框的背景色，如果它的值为true，则用fllColor属性指定的颜色作为输人框的背景色。fllColor属性用 于设置输人框的背景颜色，它的属性值类型为Color类型.

 *
 *
 * */
